#!/bin/bash
set -u
APP_ROOT="$(cd "$(dirname "$0")/../.." >/dev/null 2>&1 && pwd)"
RES_DIR="$APP_ROOT/Contents/Resources"
UI="$RES_DIR/pzsupport-ui.js"
ENGINE="$RES_DIR/pzsupportagent-mac.js"
LOG_DIR="$HOME/Library/Logs/PZSupport"
LOG_FILE="$LOG_DIR/PZSupportAgent.log"
mkdir -p "$LOG_DIR" >/dev/null 2>&1 || true
export PZ_SUPPORT_RES_DIR="$RES_DIR"

if [ ! -f "$UI" ] || [ ! -f "$ENGINE" ]; then
  /usr/bin/osascript -e 'display dialog "PZ Support Agent está incompleto. Vuelve a descargar el paquete desde PZ Support Cloud." buttons {"Cerrar"} default button "Cerrar" with icon stop' >/dev/null 2>&1 || true
  exit 2
fi

# Intento principal: Branded UI.
/usr/bin/osascript -l JavaScript "$UI" >>"$LOG_FILE" 2>&1
RC=$?
[ "$RC" -eq 0 ] && exit 0

# Fallback de campo: si Cocoa/JXA no puede presentar la UI moderna,
# nunca dejamos una sesión invisible. Se mantiene un panel AppleScript visible.
echo "[$(date '+%Y-%m-%d %H:%M:%S')] UI startup failed rc=$RC; entering visible fallback" >>"$LOG_FILE"
PIN=$(/usr/bin/osascript <<'APPLESCRIPT'
try
  set d to display dialog "PZ Support Agent\n\nModo compatible activo.\n\nIngresa el PIN de soporte:" default answer "" buttons {"Cancelar", "Conectar"} default button "Conectar" with icon note
  return text returned of d
on error number -128
  return ""
end try
APPLESCRIPT
)
PIN="$(printf '%s' "$PIN" | tr -cd '0-9')"
if [ ${#PIN} -ne 6 ]; then
  /usr/bin/osascript -e 'display dialog "PIN inválido. Debe contener 6 dígitos." buttons {"Cerrar"} default button "Cerrar" with icon caution' >/dev/null 2>&1 || true
  exit 3
fi
/bin/rm -f "$HOME/Library/Application Support/PZSupportAgent/stop.request" >/dev/null 2>&1 || true
/usr/bin/osascript -l JavaScript "$ENGINE" "$PIN" >>"$LOG_FILE" 2>&1 &
ENGINE_PID=$!
/usr/bin/osascript <<'APPLESCRIPT'
display dialog "PZ Support Agent está activo y conectado en segundo plano.\n\nEl técnico puede ejecutar diagnósticos desde PZ Support Cloud.\n\nMantén esta ventana abierta durante la asistencia." buttons {"Desconectar y salir"} default button "Desconectar y salir" with icon note giving up after 86400
APPLESCRIPT
/bin/mkdir -p "$HOME/Library/Application Support/PZSupportAgent" >/dev/null 2>&1 || true
/bin/printf stop > "$HOME/Library/Application Support/PZSupportAgent/stop.request"
wait "$ENGINE_PID" >/dev/null 2>&1 || true
exit 0
